package com.whsr.readservice.controller;


import com.whsr.readservice.util.VerifyCode;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/server/login/")
public class LoginController {

    private Map<String, Object> resultMap = new HashMap<>();

    @RequestMapping("verifyCode/{timestamp}")
    public void getVerifyCode(@PathVariable String timestamp, HttpServletRequest req, HttpServletResponse res){
        try {
            //创建对象
            VerifyCode vc = new VerifyCode();
            //获取图片对象
            BufferedImage bi = vc.getImage();
            //获得图片的文本内容
            String text = vc.getText();
            // 将系统生成的文本内容保存到session中
            req.getSession().setAttribute("text", text);
            //向浏览器输出图片
            vc.output(bi, res.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("login")
    @ResponseBody
    public Object login(@RequestBody Map<String, Object> paramMap, HttpServletRequest req){
        try {
            resultMap = new HashMap<>();
            String loginName = String.valueOf(paramMap.get("loginName"));
            String pwd = String.valueOf(paramMap.get("pwd"));
            String verifycode = String.valueOf(paramMap.get("verifycode"));
            HttpSession session = req.getSession();
            boolean iscode = session.getAttribute(verifycode) == null ? true : false;
            if(iscode){
                session.removeAttribute(verifycode);
            }else{
                throw new Exception("验证码有误!");
            }
            if(!"admin".equals(loginName)){
                throw new Exception("登陆账号有误!");
            }else if(!"asdfzxcvqwe".equals(pwd)){
                throw new Exception("登陆密码有误!");
            }else{
                Map<String, String> map = new HashMap<>();
                map.put("loginName", loginName);
                map.put("pwd", pwd);
                session.setAttribute("CURRENT_USER", map);
                resultMap.put("errno", 0);
                resultMap.put("msg", "登陆成功!");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("errno", 10001);
            resultMap.put("msg",e.getMessage());
        }
        return resultMap;
    }

}
